package com.redisson.config;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.util.CharsetUtil;
import org.redisson.client.codec.BaseCodec;
import org.redisson.client.handler.State;
import org.redisson.client.protocol.Decoder;
import org.redisson.client.protocol.Encoder;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @program: MultiProject
 * @description: 自定义序列化
 * @author: liangshuai
 * @create: 2020-11-10 10:05
 **/
public class CustomerCodec extends BaseCodec {

    public static final CustomerCodec INSTANCE = new CustomerCodec();

    private final Charset charset;

    private final Encoder encoder = new Encoder() {
        @Override
        public ByteBuf encode(Object in) throws IOException {
            ByteBuf out = ByteBufAllocator.DEFAULT.buffer();

            out.writeCharSequence(JSON.toJSONString(in), charset);
            return out;
        }
    };

    private final Decoder<Object> decoder = new Decoder<Object>() {
        @Override
        public Object decode(ByteBuf buf, State state) {
            String str = buf.toString(charset);
            buf.readerIndex(buf.readableBytes());
            return str;
        }
    };

    public CustomerCodec() {
        this(CharsetUtil.UTF_8);
    }

    public CustomerCodec(ClassLoader classLoader) {
        this();
    }

    public CustomerCodec(String charsetName) {
        this(Charset.forName(charsetName));
    }

    public CustomerCodec(Charset charset) {
        this.charset = charset;
    }

    @Override
    public Decoder<Object> getValueDecoder() {
        return decoder;
    }

    @Override
    public Encoder getValueEncoder() {
        return encoder;
    }


}
